package com.example.springsecurity.handler;

import com.example.springsecurity.security.mapper.UserMapper;
import com.example.springsecurity.security.pojo.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Component
public class LoginSuccessHandler implements AuthenticationSuccessHandler {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private UserMapper userMapper;
    /**
     *
     * @param request
     * @param response
     * @param authentication 保存了我们登录后的用户信息
     */
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request,
                                        HttpServletResponse response,
                                        Authentication authentication) throws IOException, ServletException {
        //在这里我们可以在查询一下数据库  然后返回我们想要的用户数据即可
        User user = userMapper.selectByName(authentication.getName());

        //authentication.getPrincipal() : 获取登录后的用户信息
        logger.info("登陆成功 : {}",authentication.getPrincipal());
        response.setStatus(HttpServletResponse.SC_OK);//200状态码
        response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);//设置请求头为 application/json;charset=UTF-8
        PrintWriter writer = response.getWriter();
//        writer.write("登录成功 : " + authentication.getPrincipal());
        writer.write("登录成功 : " + user);
        writer.flush();
        writer.close();
    }
}
